const request = require('superagent');

function ajax(options) {
  const defaults = {
    url: '',
    type: 'post',
    data: {},
    header: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  };

  options = Object.assign({}, defaults, options);

  const promise = request[options.type](options.url).withCredentials();

  Object.keys(options.header).forEach((key) => {
    promise.set(key, options.header[key]);
  });

  promise.timeout({
    response: 20000,
    deadline: 60000
  });

  promise.send(options.data);

  console.log(`\n=== super agent request [${new Date().toLocaleString()}] ===\n`, options,
    '\n==================================================\n');

  promise.then((a) => {
    console.log(`\n=== super agent response [${new Date().toLocaleString()}] ===\n`, JSON.stringify(a),
    '\n=================================================\n');
  });

  return promise;
}

ajax.responseError = (ctx, msg, status = 500) => {
  ctx.status = status;
  ctx.body = {
    success: false,
    errorMsg: msg,
    value: null
  }
};

ajax.responseSuccess = (ctx, value, status = 200) => {
  ctx.status = status;
  ctx.body = {
    success: true,
    errorMsg: '',
    value,
  }
};

module.exports =  ajax;
